package com.beijiteshop.shop.ui.order.adapter

import android.view.View
import com.beijiteshop.shop.R
import com.beijiteshop.shop.databinding.ItemCouponSelectBinding
import com.beijiteshop.shop.model.api.response.Coupon
import com.beijiteshop.shop.model.entity.CheckBoxEntity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/9 16:42
 * @Description 优惠券选择列表适配器
 */
class CouponSelectAdapter(data: MutableList<CheckBoxEntity<Coupon>>)
    : BaseQuickAdapter<CheckBoxEntity<Coupon>,BaseDataBindingHolder<ItemCouponSelectBinding>>(R.layout.item_coupon_select,data) {

    init {
        addChildClickViewIds(R.id.coupon_select_use_tv)
    }

    override fun convert(holder: BaseDataBindingHolder<ItemCouponSelectBinding>, item: CheckBoxEntity<Coupon>) {
        holder.dataBinding?.let {
            it.isSelect = item.isSelected
            it.coupon = item.data
        }
    }

    override fun setOnItemChildClick(v: View, position: Int) {
        super.setOnItemChildClick(v, position)
        //设置item的选中、未选择状态
        val curPosition = getCurSelectPosition()
        if (curPosition != -1 && curPosition != position){
            data.forEachIndexed { index, checkBoxBean ->
                checkBoxBean.isSelected = index == position
            }
            notifyItemChanged(curPosition)
            notifyItemChanged(position)
        }
    }

    /**
     * 获取当前选中的Item的position
     */
    private fun getCurSelectPosition(): Int{
        var position = -1
        data.forEachIndexed { index, checkBoxBean ->
            if (checkBoxBean.isSelected){
                position = index
            }
        }
        return position
    }

}